package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Cabinet;
import com.antdesignbackend.backend.entity.Cabinetitem;
import com.antdesignbackend.backend.entity.entityVo.CabinetitemVo;
import com.antdesignbackend.backend.service.CabinetService;
import com.antdesignbackend.backend.service.CabinetitemService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Controller
@RequestMapping("/cabinetitem")
public class CabinetitemController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();
    private Integer id;
    @Autowired
    CabinetitemService cabinetitemService;
    @Autowired
    CabinetService cabinetService;
    @Autowired
    InterfaceController interfaceController;
    /**
     *格子管理
     */
    @GetMapping("/index/{id}")
    @AuthToken
    public String index(@PathVariable int id) {
        this.id=id;
        return "cabinetitem/index";
    }
    /**
     * 表格查询
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    public ReturnVO tableSearch(@RequestBody CabinetitemVo cabinetitemVo) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        List<CabinetitemVo> cabinetitemVos=new ArrayList<>();
        QueryWrapper<CabinetitemVo> wrapper =new QueryWrapper<>();
        wrapper.eq("a.cabId",id);
        if(cabinetitemVo.getName()!=null&& !cabinetitemVo.getName().equals(""))
        {
            wrapper.eq("b.name",cabinetitemVo.getName());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=cabinetitemService.count(wrapper);
        result.setTotal(total);
        System.out.println("***************************格子满足条件的数据有："+total);
        //再查询
        if(total>=0)
        {
            System.out.println("***************************进入查询语句");
            cabinetitemVos=cabinetitemService.search(wrapper,new Page<>(cabinetitemVo.getPageIndex(),cabinetitemVo.getPageSize()));
            for(Cabinetitem cabinetitem:cabinetitemVos){
                cabinetitem.setImage(WebConfig.host+"images/"+cabinetitem.getImage());
            }
            System.out.println("***************************格子查询的数据有："+cabinetitemVos);
        }
        result.setData(cabinetitemVos);
        return result;
    }
    /**
     * 根据id删除
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteById(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (cabinetitemService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
        } else {
            result.setMessage("删除失败");
            result.setCode("0");
        }
        return result;
    }

    /**
     * 修改有货无货
     * @param
     * @return
     */
    @GetMapping("/updateType/{cabinetitemId}/{isNum}")
    public void updateType(@PathVariable Integer cabinetitemId,@PathVariable Integer isNum) {
        UpdateWrapper<Cabinetitem> cabinetitemUpdateWrapper=new UpdateWrapper<>();
        if(isNum==0){
            cabinetitemUpdateWrapper.set("isNum",1).eq("cabinetitemId",cabinetitemId);
        }else{
            cabinetitemUpdateWrapper.set("isNum",0).eq("cabinetitemId",cabinetitemId);
        }
        cabinetitemService.update(cabinetitemUpdateWrapper);
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody Cabinetitem cabinetitem, HttpServletRequest request) throws Exception {
        result = new ReturnVO();
        boolean b = false;
        if(cabinetitem.getCabinetitemId()==0){
            cabinetitem.setCabId(id);
            b=cabinetitemService.save(cabinetitem);
        }else{
            if(cabinetitem.getImage().contains("http")){
                String image = cabinetitem.getImage().substring(cabinetitem.getImage().lastIndexOf("/")+1);
                cabinetitem.setImage(image);
            }
            b=cabinetitemService.updateById(cabinetitem);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        }
        else
        {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }

    /***
     * 上传图片
     * @return
     */
    @PostMapping("/uploadImages")
    @ResponseBody
    public Map<String,String> uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8") ;
        long random =System.currentTimeMillis();
        String dateKey =random+"";
        String localPathDir="";
        String newFileName="";
        Map<String,String> map = new HashMap<>();
        if(!WebConfig.uploadImage.equals("")){
            localPathDir=WebConfig.uploadImage;
        }else{
            localPathDir= ResourceUtils.getURL("classpath:").getPath()+"images/";
        }
        File logoSaveFile = new File(localPathDir);
        if(!logoSaveFile.exists()){
            logoSaveFile.mkdirs();
        }
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            Iterator iter = mr.getFileMap().values().iterator();
            if (iter.hasNext()) {
                MultipartFile file = (MultipartFile) iter.next();
                String oname = file.getOriginalFilename();
                String fileTyle=oname.substring(oname.lastIndexOf("."),oname.length());
                fileTyle=fileTyle.toLowerCase();
                newFileName=dateKey+fileTyle;
                String fileName = localPathDir+newFileName;
                if(fileTyle.equals(".png") || fileTyle.equals(".gif") || fileTyle.equals(".jpg"))
                {
                    File files = new File(fileName);
                    InputStream inputstream =file.getInputStream();
                    byte[] bytes = new byte[1024];
                    FileOutputStream outstream = new FileOutputStream(fileName);
                    int index;
                    while ((index = inputstream.read(bytes)) != -1) {
                        outstream.write(bytes, 0, index);
                        outstream.flush();
                    }
                    outstream.close();
                    inputstream.close();
                }
            }
        }
        if(newFileName!=null && !newFileName.equals(""))
        {
            map.put("url",newFileName);
            map.put("httpUrl",WebConfig.host+"images/"+newFileName);
        }
        // System.out.println("return:"+localPathDir+newFileName);
        return map;
    }
    /**
     * 根据id开格子自研
     */
    @GetMapping("/openById/{id}")
    @ResponseBody
    public ReturnVO openById(@PathVariable Serializable id) {
        result = new ReturnVO();
        String reulsts = "Error";
        Cabinetitem cabinetitem=cabinetitemService.getById(id);
        Cabinet cabinet=cabinetService.getById(cabinetitem.getCabId());
        if(cabinet.getType()==1){
            reulsts=interfaceController.cabinetitem(Integer.parseInt(id.toString()),null);
        }else if(cabinet.getType()==2){
            reulsts=interfaceController.cabinetitemdm(Integer.parseInt(id.toString()),null);
        }
        if (reulsts.equals("OK")) {
            result.setMessage("打开成功！");
            result.setCode("200");
        } else {
            result.setMessage("打开失败！");
            result.setCode("500");
        }
        return result;
    }
}
